package hendler

import (
	"encoding/json"
	"food-expressions/cache"
	"food-expressions/model"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func List(c *gin.Context) {
	var Foods []model.Food
	title := c.Query("title")
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size

	redis_key := "list_page_" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		err := model.DB.Where("title like ?", "%"+title+"%").Offset(offset).Limit(size).Find(&Foods).Error
		jsonData, _ := json.Marshal(&Foods)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Second*120)
		if err != nil {
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "查询失败",
			})
			return
		}
	} else {
		json.Unmarshal([]byte(cacheData), &Foods)
	}
	var total int64

	model.DB.Model(&Foods).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"data":  Foods,
		"total": total,
	})
}
func FoodList(c *gin.Context) {
	var Foods []model.Food
	title := c.Query("title")
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size

	redis_key := "list_page_" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		err := model.DB.Where("title like ?", "%"+title+"%").Offset(offset).Limit(size).Find(&Foods).Error
		jsonData, _ := json.Marshal(&Foods)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Second*120)
		if err != nil {
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "查询失败",
			})
			return
		}
	} else {
		json.Unmarshal([]byte(cacheData), &Foods)
	}
	var total int64

	model.DB.Model(&Foods).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"data":  Foods,
		"total": total,
	})
}
func Add(c *gin.Context) {
	var Foods []model.Food
	title := c.Query("title")
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size

	redis_key := "list_page_" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		err := model.DB.Where("title like ?", "%"+title+"%").Offset(offset).Limit(size).Find(&Foods).Error
		jsonData, _ := json.Marshal(&Foods)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Second*120)
		if err != nil {
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "查询失败",
			})
			return
		}
	} else {
		json.Unmarshal([]byte(cacheData), &Foods)
	}
	var total int64

	model.DB.Model(&Foods).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"data":  Foods,
		"total": total,
	})
}
